package com.epam.springtest.controller;

import com.epam.springtest.domain.User;
import com.epam.springtest.service.MailService;
import com.epam.springtest.service.UserService;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.io.IOException;
import java.util.Locale;

/**
 * @author Mikalai Kisel
 */
@RequestMapping("/spring-mvc-test")
@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private MailService mailService;

    @Autowired
    MessageSource messageSource;

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login(Model uiModel) {
//        System.out.println(userService.checkUser("1@epam.com", "Kisel"));
        uiModel.addAttribute("user", new User());
        return "login";
    }

    @RequestMapping(value = "/home", method = RequestMethod.GET)
    public String home() {
        return "home";
    }

    @RequestMapping(value = "/signup", method = RequestMethod.GET)
    public String createUser(Model uiModel) {
        User user = new User();
        uiModel.addAttribute("user", user);
        return "signup";
    }

    @RequestMapping(value = "/signup", method = RequestMethod.POST)
    public String saveUser(@Valid User user, BindingResult bindingResult, Locale locale) {
        if (bindingResult.hasErrors())
            return "signup";

        mailService.sendEmail(user, locale);
        userService.insertUser(user);
        return "signup_complete";
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String checkUser(User user) {
        System.out.println(user);
        return "login";
    }

    @RequestMapping(value = "/checkUser", method = RequestMethod.POST)
    public
    @ResponseBody
    String saveCar(@RequestBody String userJson) throws IOException {
        System.out.println(userJson);
        ObjectMapper mapper = new ObjectMapper();
        User user = mapper.readValue(userJson, User.class);
        System.out.println(user.getEmail()+"  "+user.getPassword());
        return userService.checkUser(user.getEmail(), user.getPassword());
    }
}
